using Microsoft.Office.Interop.Excel;
using OrderSystem.SystemFramework;
using System;
using System.Data;
using System.IO;
using System.Reflection;

namespace OrderSystem.FormatOutput
{
	public class ExcelOperationOrderCommand
	{
		private _Application app;

		private _Workbook workBook;

		private _Worksheet workSheet;

		private object missing = Missing.Value;

		private string _startupPath = null;

		public ExcelOperationOrderCommand(string startupPath)
		{
			this._startupPath = startupPath;
			if (this._startupPath.Substring(this._startupPath.Length - 1, 1) != "\\")
			{
				this._startupPath += "\\";
			}
		}

		private void OpenExcel(string templetFile)
		{
			if (templetFile == null)
			{
				throw new ArgumentException("你指定的参数：templetFile 为空", "templetFile");
			}
			if (!File.Exists(templetFile))
			{
				throw new ArgumentException("你指定的参数：templetFile Excel模板文件不存在", "templetFile");
			}
			this.app = new ApplicationClass();
			this.app.Visible=true;
			this.workBook = this.app.Workbooks.Open(templetFile, this.missing, this.missing, this.missing, this.missing, this.missing, this.missing, this.missing, this.missing, this.missing, this.missing, this.missing, this.missing, this.missing, this.missing);
			this.workSheet = (_Worksheet)this.workBook.Worksheets[1];
		}

		public void MakeDataToExcel(string templetFile, System.Data.DataTable dtSumUp)
		{
			this.OpenExcel(templetFile);
			string defaultVersionOfOutType = AppSettings.GetDefaultVersionOfOutType("orderSumup");
			if (defaultVersionOfOutType == "1")
			{
				this.MakeDataToExcel_1(dtSumUp);
			}
		}

		private void MakeDataToExcel_1(System.Data.DataTable dtSumUp)
		{
			int num = 0;
			try
			{
				for (int i = 0; i < dtSumUp.Rows.Count; i++)
				{
					this.workSheet.Cells[4 + num, 1]= dtSumUp.Rows[i]["公司名称"].ToString() + ((dtSumUp.Rows[i]["公司名称"].ToString() == dtSumUp.Rows[i]["计划名称"].ToString()) ? "" : ("(" + dtSumUp.Rows[i]["计划名称"].ToString() + ")"));
					this.workSheet.Cells[4 + num, 2]= DateTime.Parse(dtSumUp.Rows[i]["订单日期"].ToString()).ToShortDateString();
					this.workSheet.Cells[4 + num, 3]= dtSumUp.Rows[i]["订单号"];
					this.workSheet.Cells[4 + num, 4]= dtSumUp.Rows[i]["类型"];
					this.workSheet.Cells[4 + num, 5]= dtSumUp.Rows[i]["数量"];
					this.workSheet.Cells[4 + num, 6]= dtSumUp.Rows[i]["面积"];
					this.workSheet.Cells[4 + num, 7]= DateTime.Parse(dtSumUp.Rows[i]["交货日期"].ToString()).ToShortDateString();
					num++;
				}
				this.workSheet.Columns.AutoFit();
				this.workBook.Save();
			}
			catch (Exception ex)
			{
				this.workBook.Save();
				throw ex;
			}
		}
	}
}
